<template>
  <div class="dishe">
    <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
            >新增</el-button>
         </el-col>
    </el-row>
    <!-- 表格数据 -->
      <el-table v-loading="loading" :data="disheList">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="类目" prop="category" :show-overflow-tooltip="true" />
         <el-table-column label="创建时间" prop="time" :show-overflow-tooltip="true" />
         <el-table-column label="菜品名称" prop="name" :show-overflow-tooltip="true" />
         <el-table-column label="菜品图片" prop="image">
            <template #default="scope">
              <el-image
                style="width: 40px; height: 40px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
              />
            </template>
         </el-table-column>
         <el-table-column label="价格" prop="unitprice" :show-overflow-tooltip="true" />
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" >
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" >
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
              </el-tooltip>
              <el-tooltip content="下架" placement="top" >
                <el-button type="danger" icon="Lock" v-if="scope.row.onsale" @click="handleShelves(scope.row)" >下架</el-button>
                <el-button type="warning" icon="Lock" v-else disabled >已下架</el-button>
              </el-tooltip>
            </template>
         </el-table-column>
      </el-table>
      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.page"
         v-model:limit="queryParams.limit"
         @pagination="getList"
        
      />
       

      <!-- 添加或修改配置对话框 -->
      <el-dialog :title="title" v-model="open" width="700px" append-to-body>
         <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="菜品类目" prop="category">
                        <el-select v-model="form.category" placeholder="请选择菜品类目名称" style="width: 240px">
                            <el-option
                            v-for="item in categoryOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="菜品名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入菜品名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="菜品价格" prop="unitprice">
                        <el-input v-model="form.unitprice" placeholder="qingshu菜品价格" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="单位" prop="unit">
                        <el-select v-model="form.unit" placeholder="请选择单位" @change="changeUnit" style="width: 240px">
                            <el-option
                            v-for="item in unitOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
             <el-row v-if="showCustomUnits">
                <el-col :span="12">
                     <el-form-item label="自定义单位">
                        <el-input v-model="customUnit" placeholder="请输入单位名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                     <el-form-item label="修改单位">
                        <el-button type="primary" @click="submitUnit" >提交</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="菜品图片" prop="unitprice">
               <el-upload 
                    v-model:file-list="fileList"
                    action="#"  
                    ref="uploadRef" 
                    list-type="picture-card" 
                    :auto-upload="false" 
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-change="beforeuploadShopLogo">
                    <el-icon><Plus /></el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref,onMounted } from 'vue'
import { categoryList, unitList, addUnit, uploadShopLogo, shelfDishes, shelfDishesList, downDishes, editDishes, delDishes } from '@/api/shop/shopinfor'
const { proxy } = getCurrentInstance();
const loading = ref(false)
const disheList = ref([])
const open = ref(false);
const title = ref("");
const total = ref(0);
const categoryOptions = ref([])
const unitOptions = ref([])
const showCustomUnits = ref(false)
const customUnit = ref('')
const uploadRef = ref()
// 是否修改图片
const isUploadImg = ref(false)
const form = ref({
    category:'',
    name:'',
    unitprice:'',
    unit:'',
    image:''

});
const rules = ref({
    category: [{ required: true, message: "菜品类目名称不能为空", trigger: "blur" }],
    name:[{ required: true, message: "菜品名称不能为空", trigger: "blur" }],
    unitprice:[{ required: true, message: "菜品价格不能为空", trigger: "blur" }]
});
const queryParams = ref({
    page: 1,
    limit: 10,
})
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)



onMounted(() => {
    getList()
})
// 获取菜品列表
const getList = async () => {
    loading.value = true
    const res = await shelfDishesList(queryParams.value)
    const { code,data } = res
    if(code == 200) {
        const { list } = data
        disheList.value = list
        total.value = data.total
    }else {
        proxy.msgError(res.msg)
    }
    loading.value = false
}


// 编辑菜品
const handleUpdate = (obj) => {
    getCategoryList()
    getUnitList()
    title.value = "编辑菜品";
    open.value = true
    form.value= obj
    fileList.value = [{
        url: obj.image
    }]
}


// 获取菜品分类列表
const getCategoryList =  async () => {
    const res = await categoryList()
    const { code,data } = res
    if(code == 200) {
        const { list } = data
        categoryOptions.value = list
    }
}

// 获取菜品单位列表
const getUnitList =  async () => {
    const res = await unitList()
    const { code,data } = res
    if(code == 200) {
        const { list } = data
        unitOptions.value = list
        const isIncludes = unitOptions.value.some(item => {
            return item.value === '自定义单位'
        })
        if(!isIncludes) {
            unitOptions.value.push({
                label:'自定义单位',
                value:'自定义单位'
            })
        }
    }
}

// 自定义单位
const changeUnit = (value) => {
    if(value === '自定义单位') {
        showCustomUnits.value = true
    }else {
        showCustomUnits.value = false
    }
}

// 新增单位
const submitUnit = async () => {
    if(!customUnit.value) {
        proxy.$modal.msgWarning('请输入自定义的单位名称')
    }else {
        const res = await addUnit({unit:customUnit.value})
        const { code,data} = res
        if(code === 200) {
            getUnitList()
            form.value.unit = ''
            proxy.$modal.msgSuccess('新增单位成功')
            showCustomUnits.value = false
        }else {
            proxy.$modal.msgError('新增单位失败')
        }
    }
}

// 新增菜品
const handleAdd = () => {
    getCategoryList()
    getUnitList()
    open.value = true;
    title.value = "新增菜品";
}



const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file,list) => {
    isUploadImg.value = true
    fileList.value = list
}
// 上传之前显示logo
const beforeuploadShopLogo = (file,list) => {
    fileList.value = list
    // ruleFormRef.value.validateField('logo')
}


// 提交菜品
const submitForm = () => {
    if(!isUploadImg.value) {
        submitShopInfor(form.value.image,form.value._id)
    }else {
        // 上传图片
        uploadImg()
    }
    
}

// 上架菜品
const submitShopInfor = async (image,id) => {
    let cate = categoryOptions.value.filter(item => {
        return item.value === form.value.category
    })
    let category = cate.length > 0 ? cate[0].cid : ''
    const obj = {
        id:id || '',
        category:form.value.category,
        name:form.value.name,
        unitprice:form.value.unitprice,
        unit:form.value.unit,
        image,
        value:category
    }
    if(title.value === '新增菜品') {
        const res = await shelfDishes(obj)
        if(res.code === 200) {
            proxy.$modal.msgSuccess(`新增菜品成功`)
            open.value = false
            reset()
            getList()
        }else {
            proxy.$modal.msgError(`新增菜品失败`)
        }
    }else {
        const res = await editDishes(obj)
        if(res.code === 200) {
            proxy.$modal.msgSuccess(`修改菜品成功`)
            open.value = false
            reset()
            getList()
        }else {
            proxy.$modal.msgError(`修改菜品失败`)
        }
    }
    
}


// 下架菜品
const handleShelves = async (shelves) => {
    console.log(shelves);
    const { _id, cid } = shelves
    const data = { 
        id:_id,
        value:cid
     }
    const res = await downDishes(data)
    if(res.code === 200) {
        proxy.$modal.msgSuccess('下架菜品成功')
        getList()
    }else {
        proxy.$modal.msgError('下架菜品失败')
    }
}

// 上传图片
const uploadImg = async () => {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    const res = await uploadShopLogo(formData)
    const { data } = res
    if(data) {
        submitShopInfor(data)
    }else {
        proxy.$modal.msgError("上传图片失败");
    }
}


// 删除菜品
const handleDelete = async (row) => {
    console.log(row);
    const dishe = row.name
    const data = {
        id: row._id,
        value: row.cid
    }
    proxy.$modal.confirm('是否确认删除菜品名为"' + dishe + '"的数据项?').then(function () {
        return delDishes(data);
    }).then((res) => {
        if (res.code == 200) {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        } else {
            proxy.$modal.msgError('删除失败');
        }
    }).catch(() => {});
}


/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    category:'',
    name:'',
    unitprice:'',
    unit:'',
    image:''
  };
  customUnit.value =''
  // 清除已经上出的文件
  uploadRef.value.clearFiles()
  fileList.value = []
  proxy.resetForm("roleRef");
}
</script>

<style lang='scss' scoped>
.dishe {
    width: 100%;
    height: 100%;
    padding: 20px;
}
</style>